/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.trick.admin.task;

import it.trick.admin.model.ContentsBaseModel;
import it.trick.admin.model.ChannelModel;
import it.trick.admin.service.CategoryService;
import it.trick.admin.service.ChapterService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.control.TreeItem;

/**
 *
 * @author takahara
 */
public class LoadCategoryTreeTask extends Service<TreeItem<ContentsBaseModel>> {

    private ChannelModel channelModel;

    /**
     * 初期化
     * @param channelModel
     */
    public void setup(ChannelModel channelModel) {
        this.channelModel = channelModel;
    }

    @Override
    protected Task createTask() {
        return new Task<TreeItem<ContentsBaseModel>>() {
            @Override
            protected TreeItem<ContentsBaseModel> call() throws Exception {

                // Root Tree Node の作成
                ContentsBaseModel rootModel = new ContentsBaseModel();
                rootModel.setKeyValueString(channelModel.getKeyValueString());

                TreeItem<ContentsBaseModel> treeItemRoot = new TreeItem(rootModel);

                // Captegory
                for(ContentsBaseModel categoryModel : CategoryService.getList(channelModel.getKeyValueString())) {
                    categoryModel.setPrarentKeyString(channelModel.getKeyValueString());
                    TreeItem<ContentsBaseModel> categoryItem = new TreeItem(categoryModel);

                    // Chapter
                    for(ContentsBaseModel chapterModel : ChapterService.getList(categoryModel.getKeyValueString())) {
                        chapterModel.setPrarentKeyString(categoryModel.getKeyValueString());
                        TreeItem<ContentsBaseModel> chapterItem = new TreeItem(chapterModel);
                        categoryItem.getChildren().add(chapterItem);
                    }

                    treeItemRoot.getChildren().add(categoryItem);
                }

                return treeItemRoot;
            }
        };
    }
}
